define(['app'], function(app) {
    app.controller('copyFile', function($http, $uibModalInstance, toastr, _context, _dialog) {
        var self = this;

        self.init = function() {
            self.source = _context.path;
            self.directory = '';
            var dotIndex = _context.name.lastIndexOf('.');
            if (dotIndex == -1) {
                self.target = _context.name + '-副本';
            } else {
                self.target = _context.name.substring(0, dotIndex) + '-副本'
                            + _context.name.substring(dotIndex);
            }
            self.ignored = true;
            self.movable = false;
            self.selectedNode = null;
        }

        self.select = function(path, node) {
            self.directory = path;
            self.selectedNode = node;
        }

        self.submit = function(valid) {
            if (valid) {
                var module = self.directory;
                var target = self.target;
                var slashIndex = self.directory.indexOf('/');
                if (slashIndex != -1) {
                    module = self.directory.substring(0, slashIndex);
                    target = self.directory.substring(slashIndex + 1) + '/' + self.target;
                }
                // copy folder
                $http.post('/note/data/copy', {
                    type: 'file',
                    module: module,
                    source: self.source,
                    target: target,
                    ignored: self.ignored,
                    movable: self.movable
                }).then(function(response) {
                    setTimeout(function() {
                        if (response.data == 'required') {
                            _dialog.alert('提示信息', '模块【' + module + '】不存在！');
                        } else if (response.status == 200) {
                            toastr.success('文件【' + self.target + '】已复制！');
                            $uibModalInstance.close({
                                deleted: self.movable, addNode: self.selectedNode
                            });
                        }
                    }, 500);
                });
            }
        }

        self.cancel = function() {
            $uibModalInstance.dismiss();
        }
    });
});
